package controllers

import (
    "encoding/json"
    "github.com/beego/beego/v2/server/web"
    "volux/utils"
)

// SubsystemController 处理子系统相关请求
type SubsystemController struct {
    web.Controller
}

type Subsystem struct {
    NQN         string   `json:"nqn"`
    AllowedHosts []string `json:"allowed_hosts"`
    Description string   `json:"description"`
}

// GetSubsystems 获取所有子系统
func (c *SubsystemController) GetSubsystems() {
    // TODO: 实现获取子系统列表的逻辑
    c.Data["json"] = []Subsystem{}
    c.ServeJSON()
}

// CreateSubsystem 创建新的子系统
func (c *SubsystemController) CreateSubsystem() {
    var subsystem Subsystem
    if err := json.Unmarshal(c.Ctx.Input.RequestBody, &subsystem); err != nil {
        utils.ErrorResponse(c.Controller, 400, "Invalid request body")
        return
    }

    spdkClient := utils.GetSPDKClient()
    if (spdkClient == nil) {
        utils.ErrorResponse(c.Controller, 500, "SPDK client not available")
        return
    }

    // 使用 SPDK 客户端创建子系统
    resp, err := spdkClient.Call("nvmf_create_subsystem", map[string]interface{}{
        "nqn": subsystem.NQN,
        "allow_any_host": false,
        "hosts": subsystem.AllowedHosts,
    })
    if err != nil {
        utils.ErrorResponse(c.Controller, 500, "Failed to create subsystem")
        return
    }
    
    if resp.Error != nil {
        utils.ErrorResponse(c.Controller, 500, resp.Error.Message)
        return
    }

    utils.SuccessResponse(c.Controller, subsystem)
}

// GetSubsystem 获取特定子系统
func (c *SubsystemController) GetSubsystem() {
    nqn := c.Ctx.Input.Param(":nqn")
    if nqn == "" {
        c.Data["json"] = map[string]interface{}{"error": "NQN is required"}
        c.ServeJSON()
        return
    }

    // TODO: 实现获取单个子系统的逻辑
    c.Data["json"] = Subsystem{NQN: nqn}
    c.ServeJSON()
}

// UpdateSubsystem 更新特定子系统
func (c *SubsystemController) UpdateSubsystem() {
    nqn := c.Ctx.Input.Param(":nqn")
    if nqn == "" {
        c.Data["json"] = map[string]interface{}{"error": "NQN is required"}
        c.ServeJSON()
        return
    }

    var subsystem Subsystem
    if err := json.Unmarshal(c.Ctx.Input.RequestBody, &subsystem); err != nil {
        c.Data["json"] = map[string]interface{}{"error": "Invalid request body"}
        c.ServeJSON()
        return
    }

    // TODO: 实现更新子系统的逻辑
    c.Data["json"] = map[string]interface{}{"message": "Subsystem updated"}
    c.ServeJSON()
}

// DeleteSubsystem 删除特定子系统
func (c *SubsystemController) DeleteSubsystem() {
    nqn := c.Ctx.Input.Param(":nqn")
    if nqn == "" {
        c.Data["json"] = map[string]interface{}{"error": "NQN is required"}
        c.ServeJSON()
        return
    }

    // TODO: 实现删除子系统的逻辑
    c.Data["json"] = map[string]interface{}{"message": "Subsystem deleted"}
    c.ServeJSON()
}